
'use strict';

// This gulpfile makes use of new JavaScript features.
// Babel handles this without us having to do anything. It just works.
// You can read more about the new JavaScript features here:
// https://babeljs.io/docs/learn-es2015/
require('events').defaultMaxListeners=0;

import path from 'path';
import fs from 'fs';
import gulp from 'gulp';
import del from 'del';
import merge from 'merge-stream';
import process from 'process';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import runSequence from 'run-sequence';
import browserSync from 'browser-sync';
import gulpLoadPlugins from 'gulp-load-plugins';
import requireDirectory from 'require-directory';
import sprintf from "sprintf";


//import rollup from 'rollup-stream';
var rollup = require("rollup").rollup;
import rollupLoadPlugins from 'rollup-load-plugins';

var gulpTools=requireDirectory(module, './gulp-tools');

const $ = gulpLoadPlugins();
const $2 = rollupLoadPlugins();

function traverse(srcpath) {
  return fs.readdirSync(srcpath).filter(function(file) {
    return fs.statSync(path.join(srcpath, file)).isDirectory();
  });
}

function deptraverse(srcpath) {
	var ls=fs.readdirSync(srcpath);
	var ret=["."];
	for (let i=0; i<ls.length; ++i){
        let fn=ls[i];
		let ffn=path.join(srcpath, fn);
		if (fs.statSync(ffn).isDirectory()){
			ret.push(path.relative(srcpath,ffn));
			ls.concat(fs.readdirSync(ffn));
		};
	}
	return ret;
}

var pages=[];

const root=path.dirname(__filename);
console.log($2);
function pageJob(page){
	console.log('detected page:', page);
	var task=page;
    var tasks=[];

	var outDir="./dist/"+(page=="index"?"":page);
    var inDir=sprintf('./pages/%s/', page);

	gulp.task(task+'_res', ()=>
		gulp.src("./pages/"+page+"/**/*.!(jade|scss|js)", {
			dot: true
		})
			.pipe($.changed(outDir))
			.pipe(gulp.dest(outDir))
			.pipe($.size({title: 'copy'}))
	);
	tasks.push(task+'_res');

	gulp.task(task+'_pug', ()=>merge(deptraverse(inDir).map((subpath)=>{
        console.log(sprintf("./pages/%s/%s/%s@(.jade|.pug)", page, subpath, path.basename(path.join(inDir,subpath))))
        return gulp.src(sprintf("./pages/%s/%s/%s@(.jade|.pug)", page, subpath, path.basename(path.join(inDir,subpath))))
			.pipe($.jade({basedir:root}))
			.pipe($.newer(path.join(outDir, subpath)))
            .pipe($.rename('index.html'))
			.pipe(gulp.dest(path.join(outDir, subpath)))}
    )));
	tasks.push(task+"_pug");

	gulp.task(task+'_template', ()=>
		gulp.src(sprintf("./pages/%s/**/@(template_)*@(.jade|.pug)", page))
			.pipe(gulpTools.jadeWrapper())
			.pipe($.newer(path.join(outDir, "template.js")))
			.pipe($.concat("template.js"))
			.pipe(gulp.dest(outDir))
	);
	tasks.push(task+"_template");


    gulp.task(task+'_es', ()=>
        rollup({entry: sprintf("./pages/%s/%s.js", page,page),
            sourceMap:true,
            plugins: [
                $2.babel({
                    exclude: 'node_modules/**', babelrc: false,
                    presets: [
                    	//["es2015-rollup"]
                        ["es2015",{"modules":false}]
                    ],
                    plugins: ['transform-async-to-generator'],
                    runtimeHelpers: true
                }),
                $2.includepaths({paths: ["./"]}),
                //$2.nodeResolve({jsnext:true}),
                //$2.commonjs()
                //$2.autoTransform(),
                //$2.nodeGlobals(),
                $2.nodeBuiltins(),
                $2.nodeResolve({ jsnext: true, main: true, browser: true }),
                $2.commonjs(),
				//$2.json()
            ]
        }).then((bundle)=>bundle.write({
        	format: "es",
			dest: outDir+"/"+page+".js",
            sourceMap: true
		}))
			/*
            .pipe(source(page+".js","./pages/"+page))
			.pipe(buffer())
            .pipe($.sourcemaps.init({loadMaps: true}))
            .pipe($.sourcemaps.write('.'))
			.pipe(gulp.dest(outDir))*/
	);
	tasks.push(task+'_es');

    gulp.task(task+'_scss', ()=>{
		const AUTOPREFIXER_BROWSERS = [
			'ie >= 10',
			'ie_mob >= 10',
			'ff >= 30',
			'chrome >= 34',
			'safari >= 7',
			'opera >= 23',
			'ios >= 7',
			'android >= 4.4',
			'bb >= 10'
		];
		return gulp.src("./pages/"+page+"/"+page+".scss")
			.pipe($.newer('.tmp/pages/'+page+"/styles"))
			.pipe($.sourcemaps.init())
			.pipe($.sass({
			  precision: 10
			}).on('error', $.sass.logError))
			.pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
			.pipe(gulp.dest('.tmp/pages/'+page+"/styles"))
			// Concatenate and minify styles
			.pipe($.if('*.css', $.cssnano()))
			.pipe($.size({title: 'styles'}))
			.pipe($.sourcemaps.write('./'))
			.pipe(gulp.dest(outDir));
	});
	tasks.push(task+'_scss');

    gulp.task(page,cb=>runSequence(tasks,cb))
    pages.push(page);
}
traverse('./pages').map(pageJob);

// Optimize images
gulp.task('images', () =>
  gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}))
);

// Copy all files at the root level (app)
gulp.task('sync_lib', () =>
	gulp.src([
		'lib/**/*.*',
	], {
		dot: true
	}).pipe(gulp.dest('dist/lib'))
		.pipe($.size({title: 'copy'}))
);
gulp.task('sync_app', () =>
	gulp.src([
		'app/**/*.*',
	], {
		dot: true
	}).pipe(gulp.dest('dist/app'))
		.pipe($.size({title: 'copy'}))
);

// Clean output directory
gulp.task('clean', () => del(['.tmp', 'dist/*', '!dist/.git'], {dot: true}));

// Build production files, the default task
gulp.task('H5', ['clean'], cb =>
  runSequence(
  	"sync_app","sync_lib",
    pages,
	//"upload",
    cb
  )
);

